package com.step.ems.pages.login

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.step.ems.api.ApiService
import com.step.ems.api.req.LoginReq
import com.step.ems.api.res.LoginRes
import com.step.ems.common.DataStoreUtil
import com.step.ems.common.UiState
import com.step.ems.common.launch
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class LoginViewModel @Inject constructor(
    private val apiService: ApiService,
    private val dataStoreUtil: DataStoreUtil
) : ViewModel() {
    var username by mutableStateOf("")
    var password by mutableStateOf("")

    private val _loginState = MutableStateFlow<UiState>(UiState.Empty)
    val loginState = _loginState.asStateFlow()

    init {
        viewModelScope.launch {
            username = dataStoreUtil.getUsername() ?: ""
            password = dataStoreUtil.getPassword() ?: ""
        }
    }

    fun login(toHome: () -> Unit) {
        launch(state = _loginState) {
            _loginState.value = UiState.Loading()
            val res: LoginRes = apiService.login(LoginReq(username, password)).get()
            res.username = username
            res.password = password
            dataStoreUtil.saveLoginInfo(res)
            _loginState.value = UiState.Success
            toHome()
        }
    }
}